package com.ship.common.core.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.io.grpc.internal.JsonUtil;
import com.ship.common.core.domain.R;
import com.ship.common.core.utils.bean.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author tangshixuan
 * @date 2023-9-4
 */
@Component
public class HttpRequestUtil {

    @Value("${file_server.host}")
    private String fileServerHost;
    @Value("${ocr_server.host}")
    private String ocrServerHost;
    protected Log log = LogFactory.getLog(HttpRequestUtil.class);
    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    private static final String OCR_PATH = "/methedtest";

    /**
     * 上传附件MultipartFile
     * @param file
     * @return
     */
//    public String upload(MultipartFile file){
//        String result = "";
//        try {
//            InputStreamResource isr = new InputStreamResource(file.getInputStream(),
//                    file.getOriginalFilename());
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("file", isr);
//            //params.put("path", "86501729");
//            params.put("output", "json");
//            /*params.put("auth_token", "123");*/
//            String resp = HttpRequest.post(fileServerHost + FILE_UPLOAD_PATH).form(params).timeout(-1).execute().body();
//            //String resp = HttpUtil.post(fileServerHost + FILE_UPLOAD_PATH, params);
//            JSONObject re = JSONObject.parseObject(resp);
//            if(!re.getString("retcode").equals("0")){
//                throw new BusException(re.getString("retmsg"), BaseResultCode.GENERAL_ERROR);
//            }
//            result = re.getString("domain") + re.getString("path");
//        } catch (Exception e) {
//            throw new BusException("文件服务器连接失败",BaseResultCode.GENERAL_ERROR);
//        }
//        return result;
//    }

    /**
     * 上传附件 后台上船
     *
     * @param file
     * @return
     */
    public R<SysFile> upload(MultipartFile file) throws IOException {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<R<SysFile>> responseEntity = restTemplate.exchange(fileServerHost, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<R<SysFile>>() {});

        R<SysFile> responseBody = responseEntity.getBody();

        return responseBody;
    }

    public JSONObject ocr1(MultipartFile file1){
        byte[] fileContent = new byte[(int)file1.getSize()];
        try {
            InputStream fis = file1.getInputStream();
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",1);
        param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 40).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public JSONObject ocrNew1(String filePath){
        URI httpUrl = null;
        InputStream inputStream = null;
        try {
            String encodedFilePath = filePath.replace(" ", "%20");
            httpUrl = new URI(encodedFilePath);
            URL uri = httpUrl.toURL();
            inputStream = uri.openConnection().getInputStream();
        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while (true){
            try {
                if (!((len=inputStream.read(b))!=-1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            bos.write(b,0,len);
        }
        byte[] fileContent = bos.toByteArray();
        try {
            inputStream.read(fileContent);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",1);
        param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).setReadTimeout(1000 * 60 * 40)
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .timeout(1000 * 60 * 40).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public JSONObject ocrNew2(String filePath){
        URI httpUrl = null;
        InputStream inputStream = null;
        try {
            String encodedFilePath = filePath.replace(" ", "%20");
            httpUrl = new URI(encodedFilePath);
            URL uri = httpUrl.toURL();
            inputStream = uri.openConnection().getInputStream();
        } catch (IOException | URISyntaxException e) {
            throw new RuntimeException(e);
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while (true){
            try {
                if (!((len=inputStream.read(b))!=-1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            bos.write(b,0,len);
        }
        byte[] fileContent = bos.toByteArray();
        try {
            inputStream.read(fileContent);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",2);
        param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 40).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public JSONObject testocr(MultipartFile file1){
        byte[] fileContent = new byte[(int)file1.getSize()];
        try {
            InputStream fis = file1.getInputStream();
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",2);
        param.put("value",new String[]{base64String});
        try {
//            String res = HttpRequest.post("http://10.75.33.149:8309" + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 10).execute().body();
//            String res = HttpRequest.post("http://172.16.4.90:8309" + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 10).execute().body();
//            String res = HttpRequest.post("http://172.16.4.84:8309" + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 10).execute().body();
            String res = HttpRequest.post("http://106.12.241.246:8309" + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 20).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public JSONObject ocr2(MultipartFile file1){
        byte[] fileContent = new byte[(int)file1.getSize()];
        try {
            InputStream fis = file1.getInputStream();
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",2);
        param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 40).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 第三方计量Ocr识别
     * @param file 文件
     * @param fileId 文件id
     * @param contractType 第三方计量类型为3，资源合同为1，船运合同为2
     * @return
     */
    public JSONObject ocr3(MultipartFile file,String fileId,Integer contractType){
        byte[] fileContent = new byte[(int)file.getSize()];
        try {
            InputStream fis = file.getInputStream();
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id",fileId);
        param.put("contract_type",contractType);
        //param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 10).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public JSONObject updateocr(MultipartFile file1){
        byte[] fileContent = new byte[(int)file1.getSize()];
        try {
            InputStream fis = file1.getInputStream();
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id","1");
        param.put("contract_type",3);
        param.put("value",new String[]{base64String});
        try {
            String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 10).execute().body();
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                return result.getJSONObject("infos");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 解析计量报告
     * @return
     */
    public JSONObject ocrJLReport(InputStream fis,String filesId) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len=fis.read(b))!=-1){
            bos.write(b,0,len);
        }
        byte[] fileContent = bos.toByteArray();
        try {
            fis.read(fileContent);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileContent);
        JSONObject param = new JSONObject();
        param.put("file_id",filesId);
        param.put("contract_type",3);
        param.put("value",new String[]{base64String});
        JSONObject resultObject = new JSONObject();
        log.warn("开始ocr识别");
        String res = HttpRequest.post(ocrServerHost + OCR_PATH).body(JSON.toJSONString(param)).header("Content-Type","application/x-www-form-urlencoded").timeout(1000 * 60 * 20).execute().body();
        log.warn("ocr返回:    "+res);
        try {
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                //return result.getJSONObject("infos");
                JSONObject infos =  result.getJSONObject("infos");
                //System.out.println(infos);
                for(String key:infos.keySet()){
                    String mapKey = toCamelCase(key);
                    JSONObject object = infos.getJSONObject(key);
                    if(mapKey.equals("analyticalResults")){//特殊处理componet
                        JSONObject json = infos.getJSONObject(key);
                        JSONArray jsonArray = json.getJSONArray("value");

                        Map<String,String> map = new HashMap<>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String value = jsonArray.getString(i);
                            JSONArray valueArray = jsonArray.getJSONArray(i);
                            String resultValue = "";
                            for(int j=0;j<valueArray.size();j++){
                                String tempValue = valueArray.getString(j);
                                if(isNumeric(tempValue)){
                                    resultValue = tempValue;
                                    break;
                                }
                            }
                            if(value.contains("Methane")){
                                map.put("Methane (CH4)",resultValue);
                            }else if(value.contains("Ethane")){
                                map.put("Ethane (C2H6)",resultValue);
                            }else if(value.contains("Propane")){
                                map.put("Propane (C3H8)",resultValue);
                            }else if(value.contains("i-C4H10")){
                                map.put("lso Butane (i-C4H10)",resultValue);
                            }else if(value.contains("N-Butane")){
                                map.put("N-Butane(n-C4H10)",resultValue);
                            }else if(value.contains("i-C5H12")){
                                map.put("lso Pentane (i-C5H12)",resultValue);
                            }else if(value.contains("N-Pentane")){
                                map.put("N-Pentane (n-C5H12)",resultValue);
                            }else if(value.contains("C6H14")){
                                map.put("N-Hexane (n-C6H14)",resultValue);
                            }else if(value.contains("Nitrogen")){
                                map.put("Nitrogen (N2)",resultValue);
                            }else if(value.contains("Oxy9en")){
                                map.put("Oxygen (02)",resultValue);
                            }else if(value.contains("Carbon")){
                                map.put("Carbon Dioxide (C02)",resultValue);
                            }
                        }
                        JSONArray jsonArray2 = setComponentValue(map);
                        resultObject.put("component",jsonArray2.toJSONString());
                    }
                    else if(mapKey.equals("timeLog")){ //特殊处理 timeLog
                        JSONObject json =  infos.getJSONObject(key);
                        JSONArray jsonArray =  json.getJSONArray("value");
                        JSONArray jsonArray2 = new JSONArray();
                        for(int i=0;i<jsonArray.size();i++){
                            String value = jsonArray.getString(i);
                            JSONArray valueArray = jsonArray.getJSONArray(i);
                            // 存在年度信息
                            String year = "";
                            String time = "";
                            String componet = "";
                            for(int j=0;j<valueArray.size();j++){
                                String tempValue = valueArray.getString(j);
                                tempValue = tempValue.trim();
                                if(isStringYear(tempValue)){
                                    year = tempValue;
                                }else if(isValidTimeFormat(tempValue)){
                                    time = tempValue;
                                }else {
                                    componet = componet+ tempValue+" ";
                                }
                            }
                            JSONObject object1 = new JSONObject();
                            if(componet.contains("N/A")){
                                componet = componet.replace("N/A","");
                            }
                            object1.put("event",componet);
                            object1.put("date",year+" "+time);
                            jsonArray2.add(object1);
                        }
                        resultObject.put("event",jsonArray2.toJSONString());
                    }
                    else if(object!=null && object.get("value")!=null){
                        String value = object.getString("value");
                        if(StringUtils.isNotEmpty(value)){
                            if(value.contains(";")){
                                String[] tempValues = value.split(";");
                                if(tempValues.length!=4){
                                    log.error("ocr 参数格式存在错误"+key +"--"+value);
                                }
                                if(tempValues.length==4){
                                    tempValues =removeFirstElement(tempValues);
                                }
                                try{
                                    String value1 = tempValues[2];
                                    //value1 = value1.replaceAll(",","");
                                    value1 = removeUnits(value1);
                                    resultObject.put(mapKey+"Mmbtu",value1);
                                }catch (Exception e){

                                }
                                try{
                                    String value1 = tempValues[1];
                                    value1 = removeUnits(value1);
                                    //value1 = value1.replaceAll(",","");
                                    resultObject.put(mapKey+"Mt",value1);
                                }catch (Exception e){

                                }
                                try{
                                    String value1 = tempValues[0];
                                    value1 = removeUnits(value1);
                                    //value1 = value1.replaceAll(",","");
                                    resultObject.put(mapKey+"M3",value1);
                                }catch (Exception e){
                                }
                            }else{
                                value = removeUnits(value);
                                resultObject.put(mapKey,value);
                            }
                        }
                    }
                }
                return resultObject;
            }
        }catch (Exception e){
            log.error("解析 异常"+e.getMessage());
        }
        return null;
    }
    public static String[] removeFirstElement(String[] array) {
        if (array.length == 0) {
            return array; // 如果数组为空，则直接返回
        }

        String[] newArray = new String[array.length - 1];
        System.arraycopy(array, 1, newArray, 0, array.length - 1);
        return newArray;
    }

    public static JSONArray setComponentValue(Map<String,String> map){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","Methane (CH4)");
        jsonObject.put("value","");
        if(map.containsKey("Methane (CH4)")){
            jsonObject.put("value",map.get("Methane (CH4)"));
        }
        jsonObject.put("unit","%Mol");
        jsonArray.add(jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("name","Ethane (C2H6)");
        jsonObject1.put("unit","%Mol");
        jsonObject1.put("value","");
        if(map.containsKey("Ethane (C2H6)")){
            jsonObject1.put("value",map.get("Ethane (C2H6)"));
        }
        jsonArray.add(jsonObject1);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name","Propane (C3H8)");
        jsonObject2.put("unit","%Mol");
        jsonObject2.put("value","");
        if(map.containsKey("Propane (C3H8)")){
            jsonObject2.put("value",map.get("Propane (C3H8)"));
        }
        jsonArray.add(jsonObject2);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("name","lso Butane (i-C4H10)");
        jsonObject3.put("value","");
        jsonObject3.put("unit","%Mol");
        if(map.containsKey("lso Butane (i-C4H10)")){
            jsonObject3.put("value",map.get("lso Butane (i-C4H10)"));
        }
        jsonArray.add(jsonObject3);
        JSONObject jsonObject4 = new JSONObject();
        jsonObject4.put("name","N-Butane(n-C4H10)");
        jsonObject4.put("value","");
        jsonObject4.put("unit","%Mol");
        if(map.containsKey("N-Butane(n-C4H10)")){
            jsonObject4.put("value",map.get("N-Butane(n-C4H10)"));
        }
        jsonArray.add(jsonObject4);
        JSONObject jsonObject5 = new JSONObject();
        jsonObject5.put("name","lso Pentane (i-C5H12)");
        jsonObject5.put("value","");
        jsonObject5.put("unit","%Mol");
        if(map.containsKey("lso Pentane (i-C5H12)")){
            jsonObject5.put("value",map.get("lso Pentane (i-C5H12)"));
        }
        jsonArray.add(jsonObject5);
        JSONObject jsonObject6 = new JSONObject();
        jsonObject6.put("name"," N-Pentane (n-C5H12)");
        jsonObject6.put("value","");
        jsonObject6.put("unit","%Mol");
        if(map.containsKey("N-Pentane (n-C5H12)")){
            jsonObject6.put("value",map.get("N-Pentane (n-C5H12)"));
        }
        jsonArray.add(jsonObject6);
        JSONObject jsonObject7 = new JSONObject();
        jsonObject7.put("name"," N-Hexane (n-C6H14)");
        jsonObject7.put("value","");
        jsonObject7.put("unit","%Mol");
        if(map.containsKey("N-Hexane (n-C6H14)")){
            jsonObject7.put("value",map.get("N-Hexane (n-C6H14)"));
        }
        jsonArray.add(jsonObject7);
        JSONObject jsonObject8 = new JSONObject();
        jsonObject8.put("name"," Nitrogen (N2)");
        jsonObject8.put("value","");
        jsonObject8.put("unit","%Mol");
        if(map.containsKey("Nitrogen (N2)")){
            jsonObject8.put("value",map.get("Nitrogen (N2)"));
        }
        jsonArray.add(jsonObject8);
        JSONObject jsonObject9 = new JSONObject();
        jsonObject9.put("name","Oxygen (02)");
        jsonObject9.put("value","");
        jsonObject9.put("unit","%Mol");
        if(map.containsKey("Oxygen (02)")){
            jsonObject9.put("value",map.get("Oxygen (02)"));
        }
        jsonArray.add(jsonObject9);
        JSONObject jsonObject10 = new JSONObject();
        jsonObject10.put("name","Carbon Dioxide (C02)");
        jsonObject10.put("value","");
        jsonObject10.put("unit","%Mol");
        if(map.containsKey("Carbon Dioxide (C02)")){
            jsonObject10.put("value",map.get("Carbon Dioxide (C02)"));
        }
        jsonArray.add(jsonObject10);
        return jsonArray;
    }

    public static boolean isValidTimeFormat(String time) {
        return time.matches("^([01]?[0-9]|2[0-3]):[0-5][0-9]$");
    }
    public static boolean isStringYear(String inputString){
        String regex = "\\b(1[0-9]{3}|20[0-9]{2}|9999)\\b";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(inputString);
        return matcher.find();
    }

    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    public static String removeUnits(String input) {
        // 正则表达式匹配单位，这里以长度单位"cm"和体重单位"kg"为例
        // 根据需要，可以添加或修改正则表达式以匹配其他单位
        if(input.contains(",")){
            input = input.replaceAll(",","");
        }

        String regex = "\\d+(\\.\\d+)?";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
        java.util.regex.Matcher matcher = pattern.matcher(input);
        String result = "";
        if (matcher.find()) {
            result =  matcher.group();
        }
        if(input.startsWith("-")){
            result = "-"+result;
        }
        return result;
    }

    public static String toCamelCase(String str) {
        str = str.replace(" ","_");
        StringBuilder camelCaseStr = new StringBuilder();
        String[] parts = str.split("_");
        int i =0;
        for (String part : parts) {
            if(i==0){
                camelCaseStr.append(Character.toLowerCase(part.charAt(0)))
                        .append(part.substring(1).toLowerCase());
            }else{
                camelCaseStr.append(Character.toUpperCase(part.charAt(0)))
                        .append(part.substring(1).toLowerCase());
            }
            i++;
        }
        return camelCaseStr.toString();
    }

    public static void main(String[] args) {
        String res = "{\"infos\": {\"LNG Volume OCT\": {\"value\": \"953.286m3\", \"location\": {\"page\": 2, \"x1\": 785.0, \"y1\": 702.0, \"x2\": 890.0, \"y2\": 721.0}}, \"LNG Volume CCT\": {\"value\": \"171,427.249 m3\", \"location\": {\"page\": 2, \"x1\": 744.0, \"y1\": 723.0, \"x2\": 891.0, \"y2\": 747.0}}, \"LNG Volume DELIVERED\": {\"value\": \"170,474 m3\", \"location\": {\"page\": 2, \"x1\": 783.0, \"y1\": 747.0, \"x2\": 893.0, \"y2\": 772.0}}, \"Weight\": {\"value\": \"\", \"location\": {}}, \"Temperature\": {\"value\": \"-160.4℃\", \"location\": {\"page\": 2, \"x1\": 798.0, \"y1\": 798.0, \"x2\": 891.0, \"y2\": 823.0}}, \"DENSITY\": {\"value\": \"421.36 kg/m3\", \"location\": {\"page\": 2, \"x1\": 792.0, \"y1\": 846.0, \"x2\": 920.0, \"y2\": 875.0}}, \"GHV\": {\"value\": \"1,009 Btu/scf\", \"location\": {\"page\": 2, \"x1\": 806.0, \"y1\": 921.0, \"x2\": 930.0, \"y2\": 945.0}}, \"GASSING UP\": {\"value\": \"N/A;N/A;N/A\", \"location\": {\"page\": 3, \"x1\": 980.0, \"y1\": 372.0, \"x2\": 1030.0, \"y2\": 400.0}}, \"COOL DOWN\": {\"value\": \"N/A;N/A;N/A\", \"location\": {\"page\": 3, \"x1\": 980.0, \"y1\": 449.0, \"x2\": 1030.0, \"y2\": 475.0}}, \"GROSS QUANTITY\": {\"value\": \"170,474;71,830.925;3,778,156\", \"location\": {\"page\": 3, \"x1\": 161.0, \"y1\": 521.0, \"x2\": 1062.0, \"y2\": 555.0}}, \"VAPOUR\": {\"value\": \"593;249.838;13,141\", \"location\": {\"page\": 3, \"x1\": 160.0, \"y1\": 609.0, \"x2\": 1042.0, \"y2\": 635.0}}, \"NET QUANTITY\": {\"value\": \"170,474;71,581.087;3,765,015\", \"location\": {\"page\": 3, \"x1\": 160.0, \"y1\": 688.0, \"x2\": 1060.0, \"y2\": 717.0}}, \"ANALYTICAL RESULTS\": {\"value\": [[\"Methane\", \"CH4\", \"% Mol\", \"99.90\"], [\"Ethane\", \"C2H6\", \"% Mol\", \"0.02\"], [\"Propane\", \"C3H8\", \"% Mol\", \"0.00\"], [\"Iso Butane\", \"i-C4H10\", \"% Mol\", \"0.00\"], [\"N-Butane\", \"n-C4H10\", \"% Mol\", \"0.00\"], [\"Iso Pentane\", \"i-C5H12\", \"% Mol\", \"0.00\"], [\"N-Pentane\", \"n-C5H12\", \"% Mol\", \"0.00\"], [\"N-Hexane\", \"n-C6H14\", \"% Mol\", \"0.00\"], [\"Nitrogen\", \"N2\", \"% Mol\", \"0.08\"], [\"Oxygen\", \"O2\", \"% Mol\", \"Not Tested\"], [\"Carbon Dioxide\", \"CO2\", \"% Mol\", \"0.00\"]], \"location\": {\"page\": 4, \"x1\": 92.0, \"y1\": 440.0, \"x2\": 1094.0, \"y2\": 1179.0}}, \"TIME LOG\": {\"value\": [[\"2/12/2021\", \"2:00 \", \"END OF SEA PASSAGE \"], [\"2/12/2021\", \"2:00 \", \"ARRIVAL AT ANCHORAGE AREA \"], [\"7/12/2021\", \"13:45 \", \"NOTICE OF READINESS TENDERED \"], [\"2/12/2021\", \"4:42 \", \"VESSEL ANCHORED \"], [\"7/12/2021\", \"12:16 \", \"ANCHOR AWEIGHED \"], [\"7/12/2021\", \"13:45 \", \"PILOT ON BOARD \"], [\"7/12/2021\", \"13:45 \", \"DEPARTED PILOT STATION - INBOUND \"], [\"7/12/2021\", \"17:19 \", \"FIRST LINE TO SHORE \"], [\"7/12/2021\", \"18:10 \", \"VESSEL BERTHED \"], [\"7/12/2021\", \"18:10 \", \"NOTICE OF READINESS ACCEPTED \"], [\"7/12/2021\", \"18:30 \", \"GANGWAY ON BOARD \"], [\"7/12/2021\", \"18:40 \", \"COMMENCED PRELOADING /SAFETY MEETING \"], [\"7/12/2021\", \"19:10 \", \"COMPLETED PRELOADING /SAFETY MEETING \"], [\"7/12/2021\", \"20:02 \", \"COMMENCED LOADING ARMS CONNECTION \"], [\"7/12/2021\", \"20:38 \", \"COMPLETED LOADING ARMS CONNECTION  LEAK TEST \"], [\"7/12/2021\", \"20:54 \", \"WARM ESD-TEST COMPLETED \"], [\"7/12/2021\", \"20:55 \", \"OPENING CUSTODY TRANSFER INSPECTION COMPLETED \"], [\"7/12/2021\", \"21:00 \", \"COMMENCED COOL DOWN OF LOADING ARMS \"], [\"7/12/2021\", \"22:00 \", \"COMPLETED COOL DOWN OF LOADING ARMS \"], [\"7/12/2021\", \"22:12 \", \"COLD ESD-TEST COMPLETED \"], [\"7/12/2021\", \"22:24 \", \"COMMENCED LOADING OF CARGO \"], [\"7/12/2021\", \"23:04 \", \"LOADING FULL RATE \"], [\"8/12/2021\", \"16:09 \", \"COMMENCED RATE DOWN \"], [\"8/12/2021\", \"16:52 \", \"COMPLETED LOADING OF CARGO \"], [\"8/12/2021\", \"16:56 \", \"COMMENCED DRAINING \"], [\"8/12/2021\", \"17:46 \", \"COMPLETED DRAINING \"], [\"8/12/2021\", \"17:57 \", \"CLOSING CUSTODY TRANSFER INSPECTION COMPLETED \"], [\"8/12/2021\", \"20:10 \", \"COMMENCED LOADING ARMS DISCONNECTION \"], [\"8/12/2021\", \"20:15 \", \"COMPLETED LOADING ARMS DISCONNECTION \"], [\"8/12/2021\", \"20:18 \", \"VAPOR LINE DISCONNECTED \"], [\"8/12/2021\", \"20:18 \", \"LAST ARM ASHORE \"], [\"N/A\", \"N/A \", \"DOCUMENTS ON BOARD \"]], \"location\": {\"page\": 15, \"x1\": 139.0, \"y1\": 111.0, \"x2\": 920.0, \"y2\": 1007.0}}, \"BOG CONSUMED\": {\"value\": \"\", \"location\": {}}}, \"file_id\": \"1831975412531142657\", \"msg\": \"SUCCESS\", \"detect_status\": 1}\n";
        JSONObject resultObject = new JSONObject();
        try {
            JSONObject result = JSONObject.parseObject(res);
            if(result.getInteger("detect_status") == 1){
                //return result.getJSONObject("infos");
                JSONObject infos =  result.getJSONObject("infos");
                //System.out.println(infos);
                for(String key:infos.keySet()){
                    String mapKey = toCamelCase(key);
                    JSONObject object = infos.getJSONObject(key);
                    if(mapKey.equals("analyticalResults")){//特殊处理componet
                        JSONObject json = infos.getJSONObject(key);
                        JSONArray jsonArray = json.getJSONArray("value");

                        Map<String,String> map = new HashMap<>();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String value = jsonArray.getString(i);
                            JSONArray valueArray = jsonArray.getJSONArray(i);
                            String resultValue = "";
                            for(int j=0;j<valueArray.size();j++){
                                String tempValue = valueArray.getString(j);
                                if(isNumeric(tempValue)){
                                    resultValue = tempValue;
                                    break;
                                }
                            }
                            if(value.contains("Methane")){
                                map.put("Methane (CH4)",resultValue);
                            }else if(value.contains("Ethane")){
                                map.put("Ethane (C2H6)",resultValue);
                            }else if(value.contains("Propane")){
                                map.put("Propane (C3H8)",resultValue);
                            }else if(value.contains("i-C4H10")){
                                map.put("lso Butane (i-C4H10)",resultValue);
                            }else if(value.contains("N-Butane")){
                                map.put("N-Butane(n-C4H10)",resultValue);
                            }else if(value.contains("i-C5H12")){
                                map.put("lso Pentane (i-C5H12)",resultValue);
                            }else if(value.contains("N-Pentane")){
                                map.put("N-Pentane (n-C5H12)",resultValue);
                            }else if(value.contains("C6H14")){
                                map.put("N-Hexane (n-C6H14)",resultValue);
                            }else if(value.contains("Nitrogen")){
                                map.put("Nitrogen (N2)",resultValue);
                            }else if(value.contains("Oxy9en")){
                                map.put("Oxygen (02)",resultValue);
                            }else if(value.contains("Carbon")){
                                map.put("Carbon Dioxide (C02)",resultValue);
                            }
                        }
                        JSONArray jsonArray2 = setComponentValue(map);
                        resultObject.put("component",jsonArray2.toJSONString());
                    }
                    else if(mapKey.equals("timeLog")){ //特殊处理 timeLog
                        JSONObject json =  infos.getJSONObject(key);
                        JSONArray jsonArray =  json.getJSONArray("value");
                        JSONArray jsonArray2 = new JSONArray();
                        for(int i=0;i<jsonArray.size();i++){
                            String value = jsonArray.getString(i);
                            JSONArray valueArray = jsonArray.getJSONArray(i);
                            // 存在年度信息
                            String year = "";
                            String time = "";
                            String componet = "";
                            for(int j=0;j<valueArray.size();j++){
                                String tempValue = valueArray.getString(j);
                                tempValue = tempValue.trim();
                                if(isStringYear(tempValue)){
                                    year = tempValue;
                                }else if(isValidTimeFormat(tempValue)){
                                    time = tempValue;
                                }else {
                                    componet = componet+ tempValue+" ";
                                }
                            }
                            JSONObject object1 = new JSONObject();
                            if(componet.contains("N/A")){
                                componet = componet.replace("N/A","");
                            }
                            object1.put("event",componet);
                            object1.put("date",year+" "+time);
                            jsonArray2.add(object1);
                        }
                        resultObject.put("event",jsonArray2.toJSONString());
                    }
                    else if(object!=null && object.get("value")!=null){
                        String value = object.getString("value");
                        if(StringUtils.isNotEmpty(value)){
                            if(value.contains(";")){
                                String[] tempValues = value.split(";");
                                if(tempValues.length!=4){
                                  //  log.error("ocr 参数格式存在错误"+key +"--"+value);
                                }
                                if(tempValues.length==4){
                                    tempValues =removeFirstElement(tempValues);
                                }
                                try{
                                    String value1 = tempValues[2];
                                    //value1 = value1.replaceAll(",","");
                                    value1 = removeUnits(value1);
                                    resultObject.put(mapKey+"Mmbtu",value1);
                                }catch (Exception e){

                                }
                                try{
                                    String value1 = tempValues[1];
                                    value1 = removeUnits(value1);
                                    //value1 = value1.replaceAll(",","");
                                    resultObject.put(mapKey+"Mt",value1);
                                }catch (Exception e){

                                }
                                try{
                                    String value1 = tempValues[0];
                                    value1 = removeUnits(value1);
                                    //value1 = value1.replaceAll(",","");
                                    resultObject.put(mapKey+"M3",value1);
                                }catch (Exception e){
                                }
                            }else{
                                if(mapKey.equals("temperature")){
                                    System.out.println(value);
                                }
                                value = removeUnits(value);
                                resultObject.put(mapKey,value);
                            }
                        }
                    }
                }
               // return resultObject;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(resultObject);

    }
}
